package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.entity.TaskStatusTypeEntity;
import com.lkd.entity.UserEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.service.TaskStatusTypeService;
import com.lkd.utils.JsonUtil;
import com.lkd.utils.VmThreadLocalUtils;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
@Transactional
public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {

    @Autowired
    private TaskStatusTypeService statusTypeService;


    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if (!Strings.isNullOrEmpty(innerCode)) {
            qw.eq(TaskEntity::getInnerCode, innerCode);
        }
        if (userId != null && userId > 0) {
            qw.eq(TaskEntity::getUserId, userId);
        }
        if (!Strings.isNullOrEmpty(taskCode)) {
            qw.like(TaskEntity::getTaskCode, taskCode);
        }
        if (status != null && status > 0) {
            qw.eq(TaskEntity::getTaskStatus, status);
        }
        if (isRepair != null) {
            if (isRepair) {
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            } else {
                qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if (!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)) {
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime, LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page, qw));
    }


    @Override
    public List<TaskStatusTypeEntity> getAllStatus() {
        QueryWrapper<TaskStatusTypeEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .ge(TaskStatusTypeEntity::getStatusId, VMSystem.TASK_STATUS_CREATE);

        return statusTypeService.list(qw);
    }


    @Autowired
    private UserService userService;

    @Autowired
    private VMService vmService;

    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 创建工单
     *
     * @param taskViewModel
     * @return
     */
    @Override
    public boolean create(TaskViewModel taskViewModel) {

        //1、判断是否登录
//        UserVO user = userService.getUser(taskViewModel.getAssignorId());
//        if (user == null) {
//            return false;
//        }

        //判断此工单是否已经存在
        if (checkTask(taskViewModel.getInnerCode(), taskViewModel.getProductType())) {
            throw new LogicException("该机器有未完成的同类型工单");
        }


        //2、判断执行人是否存在
        UserVO user1 = userService.getUser(taskViewModel.getUserId());
        if (user1 == null) {
            throw new LogicException("执行人不纯在！");
        }

        //3、判断是否存在设备
        VmVO vmInfo = vmService.getVMInfo(taskViewModel.getInnerCode());
        if (vmInfo == null) {
            throw new LogicException("设备不纯在！");
        }

        //判断设备状态校验
        checkCreateTask(vmInfo.getVmStatus(), taskViewModel.getProductType());

        //4、创建工单表
        TaskEntity taskEntity = new TaskEntity();
        BeanUtils.copyProperties(taskViewModel, taskEntity);
        taskEntity.setAssignorId(VmThreadLocalUtils.getUser().getId());
        taskEntity.setProductTypeId(taskViewModel.getProductType());
        taskEntity.setTaskCode(generateTaskCode());
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);
        taskEntity.setRegionId(vmInfo.getRegionId());
        taskEntity.setAddr(vmInfo.getNodeAddr());
        taskEntity.setUserName(user1.getUserName());
        //taskEntity.setExpect();

        //保存工单
        this.save(taskEntity);


        //判断并保存工单详情
        List<TaskDetailsViewModel> details = taskViewModel.getDetails();
        if (!CollectionUtils.isEmpty(details) &&
                VMSystem.TASK_TYPE_SUPPLY == taskViewModel.getProductType()) {

            TaskDetailsEntity taskDetailsEntity = new TaskDetailsEntity();
            for (TaskDetailsViewModel detail : details) {
                BeanUtils.copyProperties(detail, taskDetailsEntity);
                taskDetailsEntity.setTaskId(taskEntity.getTaskId());
                taskDetailsService.save(taskDetailsEntity);
            }
        }
        //4、返回
        return true;
    }


    /**
     * 生成工单编号
     *
     * @return
     */
    private String generateTaskCode() {
        //日期+序号
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));  //日期字符串
        String key = "lkd.task.code." + date; //redis key
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) {
            redisTemplate.opsForValue().set(key, 1L, Duration.ofDays(1));
            return date + "0001";
        }
        return date + Strings.padStart(redisTemplate.opsForValue().increment(key, 1).toString(), 4, '0');
    }


    /**
     * 检验工单是否在此机器存在
     *
     * @param innerCode
     * @param productType
     * @return
     */
    private boolean checkTask(String innerCode, int productType) {

        int count = this.count(Wrappers.<TaskEntity>lambdaQuery()
                .select(TaskEntity::getTaskId)
                .eq(TaskEntity::getInnerCode, innerCode)
                .eq(TaskEntity::getProductTypeId, productType)
                .le(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_PROGRESS)

        );


        return count > 0;
    }


    /**
     * 创建工单校验
     *
     * @param vmStatus
     * @param productType
     * @throws LogicException
     */
    private void checkCreateTask(Integer vmStatus, int productType) throws LogicException {
        //如果是投放工单，状态不能为运营状态
        if (productType == VMSystem.TASK_TYPE_DEPLOY && vmStatus == VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备已在运营");
        }

        //如果是补货工单，状态必须是运营状态
        if (productType == VMSystem.TASK_TYPE_SUPPLY && vmStatus != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备不在运营状态");
        }

        //如果是撤机工单，状态必须是运营状态
        if (productType == VMSystem.TASK_TYPE_REVOKE && vmStatus != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备不在运营状态");
        }
    }


    /**
     * 接受工单
     *
     * @param taskId
     * @return
     */
    @Override
    public boolean acceptTask(Long taskId) {

        UserEntity user = VmThreadLocalUtils.getUser();
        if (user == null) {
            throw new LogicException("操作需要登录！");
        }

        //1、参数校验
        if (taskId == null) {
            throw new LogicException("参数无效");
        }

        //2、判断工单状态是否为待处理
        TaskEntity task = this.getById(taskId);
        if (task == null) {
            throw new LogicException("工单不存在！");
        }
        if (task.getTaskStatus() != VMSystem.TASK_STATUS_CREATE) {
            throw new LogicException("工单不是待处理状态！");
        }

        //3、判断执行用户是否为当前用户
        if (user.getId() != task.getUserId()) {
            throw new LogicException("非执行员工！");
        }

        //4、修改工单状态
        task.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS);
        this.updateById(task);


        return true;
    }


    /**
     * 拒绝取消工单
     *
     * @param taskId
     * @param cancelTaskViewModel
     * @return
     */
    @Override
    public boolean cancelTask(Long taskId, CancelTaskViewModel cancelTaskViewModel) {

        //1、登录校验
        UserEntity user = VmThreadLocalUtils.getUser();
        if (user == null) {
            throw new LogicException("操作需要登录！");
        }

        //2、判断工单状态是否为待处理
        TaskEntity task = this.getById(taskId);
        if (task == null) {
            throw new LogicException("工单不存在！");
        }
        if (task.getTaskStatus() == VMSystem.TASK_STATUS_FINISH ||
                task.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL) {
            throw new LogicException("工单已经结束！");
        }


        //3、判断执行用户是否为当前用户
        if (!(task.getUserId().intValue() == user.getId().intValue() ||
                task.getAssignorId().intValue() == user.getId().intValue())) {
            throw new LogicException("非执行员工！");
        }

        //4、修改订单状态
        task.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);
        task.setDesc(cancelTaskViewModel.getDesc());
        return this.updateById(task);

    }


    /**
     * 完成工单
     *
     * @param taskId
     * @return
     */
    @Override
    public boolean completeTask(Long taskId) {

        //1、登录校验
        UserEntity user = VmThreadLocalUtils.getUser();
        if (user == null) {
            throw new LogicException("操作需要登录！");
        }

        //2、判断工单状态是否为待处理
        TaskEntity task = this.getById(taskId);
        if (task == null) {
            throw new LogicException("工单不存在！");
        }
        if (task.getTaskStatus() == VMSystem.TASK_STATUS_FINISH ||
                task.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL) {
            throw new LogicException("工单已经结束！");
        }

        //3、判断执行用户是否为当前用户
        if (user.getId() != task.getUserId()) {
            throw new LogicException("非执行员工！");
        }

        //4、修改订单状态
        task.setTaskStatus(VMSystem.TASK_STATUS_FINISH);

        //工单完成，利用emq发消息更改售货机状态
        //1、运维工单：撤机(改为撤机状态)   维修、投放(改为运营状态)
        //2、运营工单：更改售货机补货时间    更改货道货物信息和补货时间

        Integer productTypeId = task.getProductTypeId();
        if (productTypeId == null) throw new LogicException("工单号为空！");

        if (productTypeId == VMSystem.TASK_TYPE_SUPPLY) {
            //补货工单
            ArrayList<SupplyChannel> supplyChannels = new ArrayList<>();
            SupplyContract supplyContract = new SupplyContract();
            supplyContract.setInnerCode(task.getInnerCode());//机器编码
            supplyContract.setSupplyData(supplyChannels);//补货数据


            List<TaskDetailsEntity> list = taskDetailsService.list(
                    Wrappers.<TaskDetailsEntity>lambdaQuery()
                            .eq(TaskDetailsEntity::getTaskId, task.getTaskId()));
            if (list != null && list.size() > 0) {
                for (TaskDetailsEntity taskDetailsEntity : list) {
                    SupplyChannel supplyChannel = new SupplyChannel();
                    BeanUtils.copyProperties(taskDetailsEntity, supplyChannel);
                    supplyChannel.setChannelId(taskDetailsEntity.getChannelCode());
                    supplyChannel.setCapacity(taskDetailsEntity.getExpectCapacity());
                    supplyChannels.add(supplyChannel);
                }
            }

            //发消息
            try {
                mqttProducer.send(TopicConfig.VMS_SUPPLY_TOPIC, 1, JsonUtil.serialize(supplyContract));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                log.error("消息投递失败！工单编号为：{}", task.getTaskId());
            }


        } else {
            //运维工单
            TaskCompleteContract taskCompleteContract = new TaskCompleteContract();
            taskCompleteContract.setTaskType(productTypeId);//工单类型
            taskCompleteContract.setInnerCode(task.getInnerCode());//机器编码

            //发消息
            try {
                mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC, 1, JsonUtil.serialize(taskCompleteContract));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                log.error("消息投递失败！工单编号为：{}", task.getTaskId());
            }
        }

        return this.updateById(task);
    }

    @Autowired
    private MqttProducer mqttProducer;
}